package cn.springboot.erp.service.impl;

import cn.springboot.erp.commons.QueryParams;
import cn.springboot.erp.commons.ResponseResult;
import cn.springboot.erp.entity.Permission;
import cn.springboot.erp.entity.RolePers;
import cn.springboot.erp.entity.UserRole;
import cn.springboot.erp.mapper.PermissionMapper;
import cn.springboot.erp.mapper.RolePersMapper;
import cn.springboot.erp.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.springboot.erp.entity.Role;
import cn.springboot.erp.service.RoleService;
import cn.springboot.erp.mapper.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author asus
* @description 针对表【role】的数据库操作Service实现
* @createDate 2024-04-29 19:10:54
*/
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RolePersMapper rolePersMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public ResponseResult rolePage(QueryParams<Role> queryParams) {
        System.out.println("queryParams = " + queryParams);
        // 获取参数
        Integer page = queryParams.getPage();
        Integer limit = queryParams.getLimit();
        Role searchParams = queryParams.getSearchParams();
        // 执行分页查询
        Page<Role> rolePage = new Page<>(page, limit);
        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
        lambda.eq(StringUtils.isNotBlank(searchParams.getRoleName()),Role::getRoleName,searchParams.getRoleName())
                .orderByDesc(Role::getCreateTime);
        baseMapper.selectPage(rolePage,lambda);

        long total = rolePage.getTotal();
        List<Role> records = rolePage.getRecords();

        return ResponseResult.Success()
                .data("total",rolePage.getTotal())
                .data("roleList",rolePage.getRecords());
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        // 根据角色id查询用户与角色关联表
        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getRoleId,id);
        List<UserRole> userRoles = userRoleMapper.selectList(lambda);
        // 如果不为空则表示角色被用户使用，不可以删除
        if (ObjectUtils.isNotNull(userRoles)){
            return ResponseResult.Fail().msg("该角色被用户使用，暂不可删除");
        }
        baseMapper.deleteById(id);
        return ResponseResult.Success().msg("角色删除成功");
    }

    @Override
    public ResponseResult selectByIdPermission(Integer id) {
        /**
         * 根据角色编号"id"查询角色权限关联表
         * 可以获取角色所具有的权限编号"permissionIds"
         */
        LambdaQueryWrapper<RolePers> rolePermissionLambda = new QueryWrapper<RolePers>().lambda();
        rolePermissionLambda.eq(RolePers::getRoleId,id);
        List<Integer> permissionIds = rolePersMapper.selectList(rolePermissionLambda).stream().map(rolePers -> rolePers.getPerId()).collect(Collectors.toList());


        /**
         * 根据权限编号"permissionIds"查询权限表
         * 可以获得角色的权限信息"permissionList"
         */
        List<Integer> permissionList = new ArrayList<>();
        if (ObjectUtils.isNotNull(permissionIds)){
            permissionList = permissionMapper.selectBatchIds(permissionIds)
                    .stream()
                    .filter(permission -> permission.getIsMenu() != 2)
                    .map(permission -> permission.getId())
                    .collect(Collectors.toList());
        }
        return ResponseResult.Success().data("permissionIds",permissionList);
    }

    @Override
    public ResponseResult updateRolePermission(Map<String, Object> map) {
        /**
         * 获取角色编号，根据角色"id"删除原有的权限"id"
         */
        Integer roleId = (Integer) map.get("roleId");

        LambdaQueryWrapper<RolePers> rolePerLambda = new QueryWrapper<RolePers>().lambda();
        rolePerLambda.eq(RolePers::getRoleId,roleId);
        rolePersMapper.delete(rolePerLambda);
        /**
         * 获取权限编号"persIds"，根据角色"id"添加权限"persIds"
         */
        List<Integer> perIds = (List<Integer>) map.get("perIds");

        perIds.forEach(perId->{
            RolePers rolePers = new RolePers();
            rolePers.setRoleId(roleId);
            rolePers.setPerId(perId);
            rolePersMapper.insert(rolePers);
        });
        return ResponseResult.Success().msg("权限分配成功");
    }
}




